package cn.gzdf.sboot04.controller;

import cn.gzdf.sboot04.entity.Emp;
import cn.gzdf.sboot04.mapper.EmpMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class EmpController {
    //此注解会创建一个实现了EmpMapper接口的类，并实例化出一个对象
    //@Autowired自动装配required = false设置为非必须，避免报编译错误
    @Autowired(required = false)
    private EmpMapper empMapper;

    @RequestMapping("/insert")
    public String insert(Emp emp){
        System.out.println("emp = " + emp);
        empMapper.insert(emp);
        return "添加完成！<a href='/list'>返回列表</a>";
    }

    @RequestMapping("/list")
    public String select(){
        //调用Mapper中的查询方法
        List<Emp> emps = empMapper.select();
        String html = "<table border=1>";
        html+="<caption>员工列表</caption>";
        html+="<tr><td>id</td><td>名字</td><td>工作</td><td>工资</td><td>操作</td></tr>";
        //添加多行员工信息
        for(Emp emp:emps){
            html+="<tr>";
            html+="<td>"+emp.getId()+"</td>";
            html+="<td>"+emp.getName()+"</td>";
            html+="<td>"+emp.getJob()+"</td>";
            html+="<td>"+emp.getSal()+"</td>";
            html+="<td><a href='/delete?id="+emp.getId()+"'>删除</a></td>";
            html+="</tr>";
        }
        html+="</table>";
        return html;
    }

    @RequestMapping("/delete")
    public String delete(Integer id){
        System.out.println("id = " + id);
        empMapper.deleteById(id);
        return "删除成功！<a href='/list'>返回列表</a>";
    }

    @RequestMapping("/update")
    public String update(Emp emp){
        System.out.println("emp = " + emp);
        empMapper.update(emp);
        return "修改成功！<a href='/list'>返回列表</a>";
    }


}
